package com.lwl.blue.commont.filet;

import com.lwl.blue.commont.base.BizException;
import com.lwl.blue.commont.base.ErrorCode;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lwl.blue.commont.base.Const.LONGIN_ATTR;

/**
 * <p>  </p>
 *
 * @Date: 2021/11/3 10:49
 * @version: V1.0
 * @Decription:
 * @author: 蓝文良
 */
public class SessionInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        //首页路径以及登录放行
        if ("/loginPage".equals(arg0.getRequestURI())) {
            return true;
        }
        //重定向
        Object object = arg0.getSession().getAttribute(LONGIN_ATTR);
        if (null == object) {
           if("/".equals(arg0.getRequestURI())
                   ||"/index".equals(arg0.getRequestURI())){
               arg1.sendRedirect("/loginPage");
               return false;
           }
            throw new BizException(ErrorCode.LOGIN_SESSION_ERROR.getCode(), ErrorCode.LOGIN_SESSION_ERROR.getMsg());
        }
        return true;
    }
}
